package com.harry.resource.workflow.module.mgr;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.SetUtils;

import com.harry.decoupling.impl.module.RestfulMgrImpl;
import com.harry.resource.inner.entity.InnerUser;
import com.harry.resource.workflow.entity.WorkFlowDefinition;
import com.harry.utility.InnerUtils;
import com.harry.utility.PoEntityHelper;
import com.harry.utility.query.InnerCriteria;

public class WorkFlowDefinitionRestfulMgr extends RestfulMgrImpl<WorkFlowDefinition> {

	@Override
	protected void persist(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, Map<String, Object> data) throws Exception {
		super.persist(params, request, response, data);
		allowedCreatingUsers(params, data);
	}

	private void allowedCreatingUsers(Map<String, Object> params, Map<String, Object> data) throws Exception {
		String[] usersCriteriaContents = PoEntityHelper.loadProperty(getEntityClass(), (String) PoEntityHelper.readValueByProperty(data, "data.id"), "initialStateDefinition.activityDefinitions.usersCriteria", null);
		Set<String> userIds = new HashSet<>();
		for (String usersCriteriaContent : usersCriteriaContents) {
			InnerCriteria userCri = de().parse(usersCriteriaContent, InnerCriteria.class);
			List<?> idValuesList = srv().query(InnerUser.class, userCri, null);
			String[] ids = InnerUtils.getQueryListFirstFieldStrings(idValuesList);
			userIds.addAll(SetUtils.unmodifiableSet(ids));
		}
		WorkFlowDefinition res = WorkFlowDefinition.class.cast(PoEntityHelper.readValueByProperty(data, "data"));
		res.setAllowedCreatingUsers(userIds.stream().map(id -> iu(id)).collect(Collectors.toSet()));
		srv().save(res);
	}

	private InnerUser iu(String id) {
		InnerUser user = new InnerUser();
		user.setId(id);
		return user;
	}
}
